import MyWorker from './worker.js?worker'

export const CHUNK_SIZE = 1024 * 1024 * 10
const THREAD_COUNT = navigator.hardwareConcurrency || 4

export async function cutFile(file) {
    return new Promise(resove => {
        // 文件分片数量
        const chunkCount = Math.ceil(file.size / CHUNK_SIZE)

        // 每个线程处理的chunk数量
        const threadChunkCount = Math.ceil(chunkCount / THREAD_COUNT)
        const result = []
        let finishCount = 0

        for (let i = 0; i < THREAD_COUNT; i++) {
            // 创建一个线程，并分配任务
            const worker = new MyWorker({
                type: 'module'
            })

            let start = i * threadChunkCount
            let end = (i + 1) * threadChunkCount
            if (end > chunkCount) {
                end = chunkCount
            }
            worker.postMessage({
                file,
                CHUNK_SIZE,
                startChunkIndex: start,
                endChunkIndex: end,
                chunkCount
            })

            worker.onmessage = e => {
                for (let i = start; i < end; i++) {
                    result[i] = e.data[i - start]
                }
                worker.terminate()
                finishCount++
                if (finishCount == THREAD_COUNT) {
                    resove(result)
                }
            }
        }
    })
}
